<!-- 医院端  新建手术跟台订单-->
<template>
  <div class="newPurchaseList-box">
    <el-container
      class="newPurchase-box"
      :class="{'add-list-newPurchase-box':curPageList.length}">
      <!-- 头部 -->
      <h3 class="title">病人信息</h3>
      <el-form
        :inline="true"
        :model="formInline"
        :rules="rulesdata"
        ref="ruleForm"
        class="demo-ruleForm-top"
        label-width="100px"
      >
        <el-form-item
          label="住院号"
          prop="admissionNumber">
          <el-input
            placeholder="请输入"
            v-model="formInline.admissionNumber"
          />
        </el-form-item>
        <el-form-item
          label="姓名"
          prop="sickName">
          <el-input
            placeholder="请输入"
            v-model="formInline.sickName"
            maxlength="11" />
        </el-form-item>
        <el-form-item
          label="性别"
          prop="sickSex">
          <!-- <el-input placeholder="请输入" v-model="formInline.sickSex"/> -->
          <el-select
            v-model="formInline.sickSex"
            placeholder="请选择">
            <el-option
              v-for="item in sickSexOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="年龄"
          prop="sickAge">
          <el-input
            placeholder="请输入"
            maxlength="3"
            @input="changeSickAge(formInline.sickAge,2)"
            v-model="formInline.sickAge"
          />
        </el-form-item>
        <el-form-item
          label="科室"
          prop="hspDept">
          <el-input
            placeholder="请输入"
            v-model="formInline.hspDept" />
        </el-form-item>
        <el-form-item
          label="手术医生"
          prop="operationDoctor">
          <el-input
            placeholder="请输入"
            v-model="formInline.operationDoctor" />
        </el-form-item>
        <el-form-item
          label="手术时间"
          prop="operationDate">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="formInline.operationDate"
            type="datetime"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item
          label="拟手术名称"
          prop="operationName">
          <el-input
            placeholder="请输入"
            v-model="formInline.operationName" />
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark">
          <el-input
            placeholder="请输入"
            v-model="formInline.remark"
            type="textarea" />
        </el-form-item>

        <el-form-item
          label="附件"
          prop="fileUrl"
          style="display:flex;"
        >
          <uploadFileMultis
            :imgsrcarr="formInline.fileUrl"
            :attr="imgBindAttr"
            @returnImgUrl="returnImgUrl"
          />
        </el-form-item>
      </el-form>
      <h3 class="title">配送信息</h3>
      <el-header
        height="auto"
        class="form-wrapper">
        <el-form
          :model="purchaseOrderInfo"
          :rules="rules"
          ref="purchaseOrderForm"
          label-width="130px"
          class="demo-ruleForm"
          :inline="true"
        >
          <el-form-item
            label="医疗机构"
            prop="hospitalId">
            <el-select
              v-model="purchaseOrderInfo.hospitalId"
              @change="getAddressList()"
              placeholder="请输入"
            >
              <el-option
                v-for="item in medicalInstitutionList"
                :key="item.companyId"
                :label="item.companyName"
                :value="item.companyId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="申请科室"
            prop="applyDeptCode">
            <el-select
              v-model="purchaseOrderInfo.applyDeptCode"
              filterable
              allow-create
              placeholder="请输入"
              remote
              clearable
              :remote-method="remoteMethod"
            >
              <el-option
                v-for="item in applyDeptList"
                :key="item.id"
                :label="item.departName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="收货地址"
            prop="receiveAddressId">
            <el-select
              :disabled="!purchaseOrderInfo.hospitalId"
              v-model="purchaseOrderInfo.receiveAddressId"
              :loading="addressLoading"
              placeholder="请选择"
              filterable
              allow-create
              remote
              clearable
              :remote-method="remoteGetAddressList"
            >
              <el-option
                v-for="(item, index) in addressList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="联系人"
            prop="concatMan">
            <el-input
              v-model="purchaseOrderInfo.concatMan"
              placeholder="请输入"
              :disabled="!purchaseOrderInfo.hospitalId"
            />
          </el-form-item>
          <el-form-item
            label="联系电话"
            prop="concatPhone">
            <el-input
              v-model="purchaseOrderInfo.concatPhone"
              placeholder="请输入"
              :disabled="!purchaseOrderInfo.hospitalId"
            />
          </el-form-item>
          <el-form-item label="供应商">
            <el-select
              clearable
              v-model="purchaseOrderInfo.upCompanyId"
              placeholder="请选择">
              <el-option
                v-for="item in changeCompanyList"
                :key="item.companyId"
                :label="item.companyName"
                :value="item.companyId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-header>
      <!-- 列表模块 添加产品-->
      <h3 class="title">添加产品</h3>
      <div
        class="top-add-button-wrapper"
        v-if="!isEmptyList">
        <div class="title-info">
          <span>已选择产品数量 : {{ checkNum }}</span>
          <span>品种数 :{{ numberOfVarieties }}</span>
          <span class="order-total-amount">
            金额合计(元) :
            <span style="color: red;">{{ formatPrice(checkMoney) }}</span>
          </span>
        </div>
        <span class="add-button">
          <el-button
            type="primary"
            @click="openAddProductDialog"
            size="small">添加产品</el-button>
          <el-button
            type="danger"
            @click="batchDelete"
            size="small">批量删除</el-button>
        </span>
      </div>
      <div>

        <el-editable
          v-if="!isEmptyList"
          v-loading="tableLoading"
          :data="tableList"
          height="500"
          :columns="purchaseOrderProductListColumns"
          @selection-change="handleSelectionChange"
        >
          <template
            slot="default-registNo"
            slot-scope="scope">
            <div>
              <cell-registration
                :key="scope.row.registNo"
                :regis-no="scope.row.registNo"
                :content="'注册证已过期，点击查看详细信息'"
                :status="scope.row.expireStatus"
                :regis-data="scope.row.registInfo"
              />
            </div>
          </template>
          <!-- 销售价格 -->
          <template
            slot="default-priceSale"
            slot-scope="scope">
            <el-input-number
              v-model="scope.row.salePrice"
              size="mini"
              :min="0"
              :max="9999999"
              :precision="3"
            />
          </template>
          <!-- 模板价格 -->
          <template
            slot="default-modelPrice"
            slot-scope="scope">
            <p>{{ Number(scope.row.modelPrice).toFixed(3) }}</p>
          </template>
          <!-- 价格差异 -->
          <template
            slot="default-priceDifference"
            slot-scope="scope">
            <p
              v-if="scope.row.salePrice"
            >{{ (Number(scope.row.salePrice) - Number(scope.row.modelPrice)).toFixed(3) }}</p>
            <p v-else>0.000</p>
          </template>
          <!-- 销售数量 -->
          <template
            slot="default-saleNum"
            slot-scope="scope">
            <el-input-number
              v-model="scope.row.count"
              size="mini"
              :step="1"
              :min="1"
              :max="9999999"
              label="描述文字"
              step-strictly
            />
          </template>
          <template
            slot="default-action"
            slot-scope="scope">
            <el-button
              size="small"
              @click.stop="deleteOrderProductItem(scope.$index)"
              type="text text-danger"
            >删除</el-button>
          </template>
        </el-editable>
      </div>
      <div
        class="center-add-button-wrapper"
        v-if="isEmptyList">
        <el-button
          type="primary"
          @click="openAddProductDialog">+ 添加产品</el-button>
      </div>
      <!-- </div> -->
      <!-- 选择采购产品 -->
      <add-product-dialog
        :dialog-visible.sync="addProductDialogShow"
        title="添加产品"
        :query-url="getAuthItemCommonQuery"
        query-method="post"
        :extra-query="sCompanyQuery"
        :current-products="purchaseOrderProductList"
        @confirmDialog="addSelectionToProductList"
        @cancelDialog="cancelAddSelection"
        :type="dialogType"
        :price-model-type="priceModelType"
      />
    </el-container>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { purchaseOrderProductListColumns, sickSexOptions } from './const'
import SearchForm from '@components/businesscomponents/search'
import ElEditable from '@components/el-editable'
import CellRegistration from '@/moduleComponents/common/detail/cell-registration'
import AddProductDialog from '@/moduleComponents/beforeSettle/hospitalSide/addProduct'
import { PAGE_NUMBER, PAGINATION_LAYOUT, PDF_LIMIT_SIZE } from '@const/common'
// import {computeRate, computeAdd} from '@const/filter'
import Addheadcontent from '@components/businesscomponents/addheadcontent'
import { formatPrice } from '@const/agencySaas'
import { cloneDeep, isObject, uniqBy, hasIn } from 'lodash'
import { getAuthItemCommonQuery } from '@const/productCenterApiV2'
import uploadFileMultis from '@components/businesscomponents/uploadFileMultis'
import {
  getAddressListAll,
  partnerList,
  createFollowOrder
} from '@const/beforeSettleApi'
import { organizationUcSearchCurr } from '@const/staffCenterApi'
const imageFileLimit = '.png,.jpg,.jpeg,.bpg,.pdf,.xls,.xlsx,.docx,.doc'
export default {
  components: {
    ElEditable,
    SearchForm,
    AddProductDialog,
    Addheadcontent,
    uploadFileMultis,
    CellRegistration
  },
  data () {
    return {
      getAuthItemCommonQuery,
      purchaseOrderProductListColumns, // 页面产品列表表头
      addProductDialogShow: false,
      addressList: [],
      addressLoading: false,
      purchaseOrderInfo: {
        concatMan: '',
        concatPhone: '',

        hospitalId: '', // 医疗机构
        applyDeptCode: '', // 科室id
        receiveAddressId: '', // 收货地址id
        upCompanyId: ''
      },
      formInline: {
        admissionNumber: '', // 住院号
        sickName: '',
        sickAge: null,
        sickSex: 0,
        hspDept: '',
        operationDoctor: '',
        operationDate: '',
        operationName: '',
        remark: '',
        fileUrl: []
      },
      sickSexOptions, // 性别
      purchaseOrderProductList: [],
      purchaseOrderProductTableList: [],
      rules: {
        hospitalId: [
          { required: true, message: '请选择医疗机构', trigger: 'change' }
        ],
        receiveAddressId: [
          { required: true, message: '请选择收货地址', trigger: 'change' }
        ],
        upCompanyId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        applyDeptCode: [
          { required: true, message: '请输入科室名称', trigger: 'change' }
        ],
        concatMan: [
          { required: true, message: '请输入联系人', trigger: 'change' }
        ],
        concatPhone: [
          { required: true, message: '请输入联系电话', trigger: 'change' }
        ]
      },
      tableLoading: false, // 这里的loading只有在扩展编辑订单功能之后才有用
      checkData: [], // 多选选中的数据
      imgBindAttr: { disabled: false },
      rulesdata: {
        admissionNumber: [
          { required: true, message: '请输入住院号', trigger: 'blur' }
        ],
        sickName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        sickAge: [
          { required: true, message: '请输入年龄(数字)', trigger: 'blur' }
        ],
        sickSex: [{ required: true, message: '请输入性别', trigger: 'blur' }],
        hspDept: [{ required: true, message: '请输入科室名称', trigger: 'blur' }],
        operationDoctor: [
          { required: true, message: '请输入手术医生名称', trigger: 'blur' }
        ],
        operationDate: [
          { required: true, message: '请选择手术日期', trigger: 'blur' }
        ],
        operationName: [
          { required: true, message: '请输入手术名称', trigger: 'blur' }
        ]
      },
      dialogType: 'followTheStage',
      applyDeptList: [],
      enclosureList: [],
      changeCompanyList: [],
      priceModelType: '0', // 0--销售  1--采购

      tableList: [], // 产品数据
      medicalInstitutionList: [] // 医疗机构数据
    }
  },
  watch: {},
  computed: {
    ...mapState(['companyId', 'companyType', 'roleType']),

    isEmptyList () {
      return this.tableList.length === 0
    },

    curPageList () {
      return this.purchaseOrderProductTableList
    },

    sCompanyQuery () {
      return {
        merchantCompanyId: this.purchaseOrderInfo.hospitalId, // 医院id
        upEnterpriseId: this.purchaseOrderInfo.upCompanyId, // 供应商id
        enterpriseId: this.$store.state.companyId// 当前公司id
      }
    },
    // 已选择产品数量
    checkNum () {
      let num = 0
      this.tableList.forEach(item => {
        num += Number(item.count)
      })
      return num
    },
    // 品种数
    numberOfVarieties () {
      return this.tableList.length
    },
    // 金额合计（元）
    checkMoney () {
      let money = 0
      this.tableList.forEach(item => {
        money += Number(item.count) * Number(item.salePrice || 0)
      })
      return money || 0
    }
  },

  mounted () {
    let obj = {
      type: 'btn',
      arr: [
        { type: 'primary', val: '确定', handle: this.toDetermine },
        { type: 'primary', val: '确定并推送', handle: this.toDeterminePush }
      ]
    }
    this.$store.commit('changeLayoutHandle', obj)

    this.getPartnerList() // 获取医疗机构和供应商
    this.remoteMethod('') // 获取科室
  },
  methods: {
    formatPrice,
    // 校验住院号
    // changeAdmissionNumber (val) {
    //   if (Number(val).toString() === 'NaN') {
    //     this.formInline.admissionNumber = val.slice(0, val.length - 1)
    //     if (Number(this.formInline.admissionNumber).toString() === 'NaN') {
    //       this.changeAdmissionNumber(this.formInline.admissionNumber)
    //     }
    //   }
    // },
    changeSickAge (val) {
      if (Number(val).toString() === 'NaN') {
        this.formInline.sickAge = val.slice(0, val.length - 1)
        if (Number(this.formInline.sickAge).toString() === 'NaN') {
          this.changeSickAge(this.formInline.sickAge)
        }
      }
    },
    // 选择医疗机构之后，获取收货地址
    getAddressList () {
      this.remoteGetAddressList('', 1)
    },
    // 模糊查询收货地址
    remoteGetAddressList (data, val) {
      this.addressLoading = true
      this.$axios
        .$post(getAddressListAll, {
          // 断数据来源；1，医院端  2，配送商端'
          yp: 1,
          companyId: this.purchaseOrderInfo.hospitalId
        })
        .then(res => {
          const list = isObject(res.payload.content) ? res.payload.content : []
          this.addressList = list.map(item => {
            let obj = {}
            obj = {
              value: item.id,
              label:
                item.province + item.city + item.area + item.detailedAddress,
              userName: item.userName,
              userPhone: item.userPhone
            }
            return obj
          })
          // 选择医疗机构之后，默认选中收货地址第一个
          if (val && this.addressList.length) {
            this.purchaseOrderInfo.receiveAddressId = this.addressList[0].value
            this.purchaseOrderInfo.concatMan = this.addressList[0].userName
            this.purchaseOrderInfo.concatPhone = this.addressList[0].userPhone
          } else if (val && !this.addressList.length) {
            this.purchaseOrderInfo.receiveAddressId = ''
            this.purchaseOrderInfo.concatMan = ''
            this.purchaseOrderInfo.concatPhone = ''
          }
        })
        .catch(e => {})
        .finally(() => {
          this.addressLoading = false
        })
    },
    toDetermine () {
      this.commitData(0)
    },
    toDeterminePush () {
      this.commitData(1)
    },
    // 提交的数据整理
    commitData (type) {
      this.$refs.purchaseOrderForm.validate(valid => {
        this.$refs.ruleForm.validate(vali => {
          if (valid && vali) {
            // 根据医院id查找医院名称
            this.medicalInstitutionList.forEach(item => {
              if (item.companyId === this.purchaseOrderInfo.hospitalId) {
                this.purchaseOrderInfo.hospitalName = item.companyName
              }
            })
            // 根据供应商id查找供应商名称
            this.changeCompanyList.forEach(item => {
              if (item.companyId === this.purchaseOrderInfo.upCompanyId) {
                this.purchaseOrderInfo.upCompanyName = item.companyName
              }
            })

            // 根据科室id查找科室名称
            let applyDeptCodeArr = this.applyDeptList.map(item => item.id)
            if (
              !applyDeptCodeArr.includes(this.purchaseOrderInfo.applyDeptCode)
            ) {
              // 因为有手动输入的科室没有id，所以科室名称就取当前的科室id
              // 否则就取科室id对应的科室名称
              this.purchaseOrderInfo.applyDept = this.purchaseOrderInfo.applyDeptCode
            } else {
              this.applyDeptList.forEach(item => {
                if (item.id === this.purchaseOrderInfo.applyDeptCode) {
                  this.purchaseOrderInfo.applyDept = item.departName
                }
              })
            }

            // 根据收货地址id查找收货地址名称
            let receiveAddressIdArr = this.addressList.map(item => item.value)
            if (
              !receiveAddressIdArr.includes(
                this.purchaseOrderInfo.receiveAddressId
              )
            ) {
              // 因为有手动输入的收货地址没有id，所以收货地址就取当前的收货地址id
              // 否则就取收货地址id对应的收货地址
              this.purchaseOrderInfo.receiveAddress = this.purchaseOrderInfo.receiveAddressId
            } else {
              this.addressList.forEach(item => {
                if (item.value === this.purchaseOrderInfo.receiveAddressId) {
                  this.purchaseOrderInfo.receiveAddress = item.label
                }
              })
            }

            // 整理产品数据
            let list = this.tableList.map(item => {
              return {
                price: item.salePrice,
                purchaseNum: item.count,
                authProdId: item.id,
                itemId: item.hosAuthItemId,
                hspProdCode: item.hosProdCode
              }
            })
            let data = {
              ...this.formInline,
              ...this.purchaseOrderInfo,
              identification: type,
              productFom: list
            }
            let fileList = this.formInline.fileUrl.map(item => {
              return {
                fileUrl: item.url,
                fileName: item.name
              }
            })
            data.fileUrl = fileList
            this.$axios({
              method: 'post',
              url: createFollowOrder,
              data: data
            }).then(res => {
              this.$router.push({
                path:
                  '/distributorSide/newSalesManagement/salesOrderTracking/operationOrder'
              })
            })
          }
        })
      })
    },
    // 获取医疗机构和供应商
    getPartnerList () {
      // 合作类型 provider供应商、customer客户 多种逗号分隔
      this.$axios({
        method: 'get',
        url: partnerList,
        params: {
          partnership: 'customer'
        }
      }).then(res => {
        this.medicalInstitutionList = res.data.payload || []
      })

      this.$axios({
        method: 'get',
        url: partnerList,
        params: {
          partnership: 'provider'
        }
      }).then(res => {
        this.changeCompanyList = res.data.payload || []
      })
    },
    // 批量删除
    batchDelete () {
      if (!this.checkData.length) {
        this.$message.warning('请选择需要删除的产品！')
        return
      }
      let removeId = this.checkData.map(item => {
        return item.id
      })
      let dataList = cloneDeep(this.tableList)
      let newArr = []
      dataList.forEach(item => {
        if (!removeId.includes(item.id)) {
          newArr.push(item)
        }
      })
      this.tableList = newArr
      this.checkData = []
    },

    // 远程搜索科室
    remoteMethod (query) {
      this.$axios({
        method: 'post',
        url: organizationUcSearchCurr,
        data: {
          departName: query
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        this.applyDeptList = obj.content
      })
    },

    // 多选
    handleSelectionChange (list) {
      this.checkData = list
    },

    // 添加附件
    returnImgUrl (imgArr) {
      this.enclosureList = []
      this.formInline.fileUrl = imgArr
      let index = 1
      this.formInline.fileUrl.forEach(item => {
        var obj = {}
        // obj.fileName = `附件${index++}`
        obj.fileName = item.name
        obj.filePath = item.url
        this.enclosureList.push(obj)
      })
    },
    // 添加产品
    openAddProductDialog () {
      this.$refs.purchaseOrderForm.validate(valid => {
        this.$refs.ruleForm.validate(vali => {
          if (valid && vali) {
            this.addProductDialogShow = true
          }
        })
      })
    },
    // 添加产品
    addSelectionToProductList (selection) {
      let oldIdList = this.tableList.map(item => item.id)
      let newIdList = selection.map(item => item.id)
      this.tableList.forEach(item => {
        if (newIdList.includes(item.id)) {
          item.count++
        }
      })
      selection.forEach(it => {
        if (!oldIdList.includes(it.id)) {
          this.tableList.push(it)
        }
      })
      this.tableList.forEach(item => {
        // 销售价格
        // if (item.modelPrice) {
        //   this.$set(item, 'salePrice', item.modelPrice)
        // }
        // 模板价格
        if (item.modelPrice) {
          this.$set(item, 'salePrice', item.modelPrice)
          // item.modelPrice = item.modelPrice
        } else {
          item.modelPrice = 0
        }
        // 销售数量
        if (!item.count) {
          this.$set(item, 'count', 1)
        }
      })
      this.addProductDialogShow = false
    },
    // 取消添加产品
    cancelAddSelection () {
      this.addProductDialogShow = false
    },
    // 删除
    deleteOrderProductItem (index) {
      this.tableList.splice(index, 1)
    }
  }
}
</script>

<style lang='less'>
.newPurchaseList-box {
  position: absolute;
  overflow: auto;
  .upEnterpriseNameBox {
    font-size: 16px;
    font-weight: 600;
  }
  .add-list-newPurchase-box {
    position: absolute;
    overflow: auto;
  }

  .newPurchase-box {
    overflow: auto;

    .form-wrapper {
      margin-top: 16px;
      margin-left: -56px;
    }

    .title {
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
    }
    .top-add-button-wrapper {
      display: flex;
      margin: 10px 0;
      justify-content: space-between;
      .title-info {
        span {
          margin-right: 16px;
        }
      }
      .order-total-amount {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .center-add-button-wrapper {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 100px 0;
    }

    .demo-ruleForm {
      // display: flex;
      // width: 500px;
      // margin-top: 16px;
      .el-select {
        width: 100%;
      }
    }
    .demo-ruleForm-top {
      margin-top: 16px;
    }
  }
}
</style>
